package com.adcc.ags.msgStore.managed;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import com.adcc.ags.msgStore.service.MsgStoreInOrderServiceImpl;
import com.adcc.utility.log.Log;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.setup.Environment;

/**
 * 报文代理Managed
 */
public class MsgProxy implements Managed {

    // 单例对象
    private static MsgProxy instance;

    // 配置文件
    private String proxyConf;

    // ActorSystem
    private ActorSystem triggerActor;

    // 告警触发器
    private ActorRef eventTrigger;

    /**
     * 构造方法
     * */
    private MsgProxy() {}

    /**
     * 单例模式
     * */
    public synchronized static MsgProxy getInstance() {
        if (instance == null) {
            instance = new MsgProxy();
        }
        return instance;
    }

    public void setProxyConf(String proxyConf) {
        this.proxyConf = proxyConf;
    }

    public ActorRef getMsgStoreActor() {
        return eventTrigger;
    }

    public void build(Environment environment) throws Exception{
        environment.lifecycle().manage(this);
    }

    public void build(Environment environment, String proxyConf) throws Exception{
        this.proxyConf = proxyConf;
        environment.lifecycle().manage(this);
    }

    @Override
    public void start() throws Exception {
        try {
            // 初始化Actor
            Config config = ConfigFactory.load(proxyConf);
            triggerActor = ActorSystem.create("EventTrigger",config.getConfig("akka").getConfig("actor"));
            eventTrigger = triggerActor.actorOf(Props.create(MsgStoreInOrderServiceImpl.class).withMailbox("event-mailbox"),"EventTrigger");
        } catch (Exception ex) {
            Log.error(MsgProxy.class.getName(), "start() error", ex);
        }
    }

    @Override
    public void stop() throws Exception {
        try {
            if (triggerActor != null) {
                triggerActor.shutdown();
            }
        } catch (Exception ex) {
            Log.error(MsgProxy.class.getName(), "stop() error", ex);
        }
    }
}
